package org.bultreebank.document_repository.impl;

import java.io.File;

import org.bultreebank.document_repository.interfaces.StorageManager;
import org.bultreebank.index.utils.Constants;
import org.bultreebank.index.utils.Utils;
import org.w3c.dom.Document;

/**
 * Default implementation of the StorageManipulationInterface 
 * @author Aneliya Tincheva
 *
 */
public class StorageManipulationImpl implements StorageManager,
Constants
{

	private String path;
	
	/**
	 * Creates an instance of the storage manager component
	 * @param indexDocsManager - manager of documents - index membership 
	 * relation 
	 * @throws Exception
	 */
	public StorageManipulationImpl(String storageLocation)
	throws Exception
	{
		path = storageLocation;
		Utils.createNewFolder(path);
	}
	
	/**
	 * Adds a document with the specified docId to the Document Repository
	 * @param docID - document identifier
	 * @param doc - document content
	 * @throws Exception
	 */
	public void addDocument(String docID, Document doc) throws Exception {
		String docContent = Utils.getStringRepresentationOfDocument(doc);
		String filePath = path + SEPARATOR +  docID;//internalDocID;
		Utils.createNewFile(filePath);
		Utils.saveFile(filePath, docContent);		
	}

	/**
	 * Removes a document with the specified docID from the Document
	 * Repository 
	 * @param docID - document identifier
	 * @throws Exception
	 */
	public void removeDocument(String docID) throws Exception {
		String filePath = path + SEPARATOR + docID;
		File f = new File (filePath);
		boolean deleted = f.delete();
		if (!deleted)
			throw new Exception("The document with ID " + docID + 
					" couldn't be deleted!");
		
	}

	/**
	 * Retrieves the document with the specified docID from the
	 * Document Repository
	 * @param docID - document identifier
	 * @return
	 * @throws Exception
	 */
	public Document retrieveDocument(String docID) throws Exception {
		String filePath = path + SEPARATOR + docID;
		String fileContent = Utils.getStringRepresentationOfFileContent(filePath);
		return Utils.getDocumentFromString(fileContent);
	}
	
}
